import mongoose from '../config/DBHelper'
import moment from 'moment'

const Schema = mongoose.Schema
const PostSchema = new Schema({
  uid: { type: String, ref: 'user' },
  title: { type: String },
  content: { type: String },
  created: { type: Date },
  catalog: { type: String },
  favs: { type: Number },
  isEnd: { type: Number, default: 0 },
  reads: { type: Number, default: 0 },
  answer: { type: Number, default: 0 },
  status: { type: Number, default: 0 },
  isTop: { type: Number, default: 0 },
  sort: { type: Number, default: 0 },
  tags: { type: Array }
})

PostSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})

PostSchema.statics = {
  /**
   * 获取文章列表数据
   * @param {Object} options 筛选条件
   * @param {String} sort 排序方式
   * @param {Number} page 分页页数
   * @param {Number} limit
   */
  getList: function (options, sort, page, limit) {
    return this.find(options).sort({ [sort]: -1 })
      .skip(page * limit)
      .limit(limit)
      .populate({
        path: 'uid',
        select: 'name isVip pic'
      })
  },
  getListCount: function (options) {
    return this.find(options).countDocuments()
  },
  findById: function (id) {
    return this.findOne({ _id: id }).populate({
      path: 'uid',
      select: '_id name isVip pic'
    })
  },
  getMyPostList: function (id, page, limit) {
    return this.find({ uid: id }).skip(page * limit).limit(limit).sort({ created: -1 })
  }
}

const PostModel = mongoose.model('post', PostSchema)

export default PostModel
